# -*- coding: utf-8 -*-
import requests
import random
import json
from hashlib import md5
import os
def transApi( from_lang, to_lang, query):
    appid = 'appid'
    appkey = 'appkey'
    try:
        endpoint = 'http://api.fanyi.baidu.com'
        path = '/api/trans/vip/translate'
        url = endpoint + path

        def make_md5(s, encoding='utf-8'):
            return md5(s.encode(encoding)).hexdigest()

        salt = random.randint(32768, 65536)
        sign = make_md5(appid + query + str(salt) + appkey)

        # Build request
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

        # Send request
        r = requests.post(url, params=payload, headers=headers)
        result = r.json()

        # Show response
        # print(json.dumps(result, indent=4, ensure_ascii=False))
        return_obj = json.dumps(result, indent=4, ensure_ascii=False)
        dict = json.loads(return_obj)
        return dict["trans_result"]
    except Exception:
        return []


def tran_file(from_lang, to_lang, file_path,done_file_num,zone_file_num):
    context = ""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.read()
    list = lines.split("\n")
    list = [x for x in list if x != ""]
    doneNum = 0
    for line in list:
        doneNum += 1
        result_list = transApi(from_lang, to_lang, line)
        for item in result_list:
            tran_line=item["dst"]
            context += tran_line + '\n'
        os.system('cls') # 清空命令行
        print("共%s个文件，当前翻译第%s个"%(zone_file_num,done_file_num))
        print("正在翻译的文件：",file_path)
        done_rate=doneNum/len(list)
        runing_line="|"+int(done_rate*50)*"█"+(50-int(done_rate*50))*" "+"|"
        print("当前文件翻译进度 %s %.2f%% (%s/%s)"%(runing_line,done_rate*100,doneNum,len(list)))
        print("原文：",line)
        print("译文：",tran_line)
    return context


def write_file( file_path, context):
    # 写入文件名
    filepath, tmpfilename = os.path.split(file_path)
    # 创建文件夹
    folder = os.path.exists('./译文')
    if not folder:
        os.makedirs('./译文')
    write_file_path = './译文/' + '【译文】' + tmpfilename.split('.')[0] + '.txt'
    with open(write_file_path, mode='w', encoding="utf-8") as f:
        f.write(context)
    print(write_file_path + '>>写入成功')


def run_run_run( from_lang, to_lang, fileList):
    print("开始翻译，从 %s 翻译为 %s ..."%(from_lang,to_lang))
    done_file_num=0
    for path in fileList:
        done_file_num+=1
        context = tran_file(from_lang, to_lang, path,done_file_num,len(fileList))
        write_file(path, context)
    os.system('cls') # 清空命令行
    print("%s个文件已翻译成功..."%len(fileList))
    print("ヾ(≧▽≦*)o")
